<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Check } from '@element-plus/icons-vue'

const router = useRoute()
const navigation = useRouter()
const noteId = ref(router.query.id)
const isEditing = ref(!!noteId.value) // 如果有ID则为编辑模式

// 表单数据
const formData = ref({
    note_title: '',
    note_content: '',
    course_id: '',
    username: ''
})

// 加载和提交状态
const loading = ref(false)
const submitting = ref(false)

// 课程列表
const courses = ref([])

// 返回笔记列表
const goBack = () => {
    navigation.push('/student/record/Note')
}

// 获取课程列表
const fetchCourses = async () => {
    try {
        const response = await axios.get('/api/student/course/')
        courses.value = response.data || []
    } catch (error) {
        console.error('获取课程列表失败:', error)
    }
}

// 获取笔记详情
const fetchNoteDetail = async () => {
    if (!noteId.value) return

    loading.value = true
    try {
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        if (!username) {
            ElMessage.error('用户未登录')
            return
        }

        formData.value.username = username

        const response = await axios.get('/api/student/course/notes/', {
            params: {
                username,
                note_id: noteId.value
            }
        })

        if (response.data && response.data.length > 0) {
            const note = response.data[0]
            formData.value = {
                ...formData.value,
                note_title: note.note_title || '',
                note_content: note.note_content || '',
                course_id: note.course_id || ''
            }
        } else {
            ElMessage.warning('未找到笔记信息')
        }
    } catch (error) {
        console.error('获取笔记详情失败:', error)
        ElMessage.error('获取笔记详情失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 提交表单
const submitForm = async () => {
    // 表单验证
    if (!formData.value.note_title.trim()) {
        ElMessage.warning('请输入笔记标题')
        return
    }

    if (!formData.value.note_content.trim()) {
        ElMessage.warning('请输入笔记内容')
        return
    }

    submitting.value = true
    try {
        // 获取用户名
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        if (!username) {
            ElMessage.error('用户未登录')
            return
        }

        formData.value.username = username

        let response

        if (isEditing.value) {
            // 更新笔记
            response = await axios.put(`/api/student/course/notes/${noteId.value}`, formData.value)
            ElMessage.success('笔记更新成功')
        } else {
            // 创建笔记
            response = await axios.post('/api/student/course/notes/', formData.value)
            ElMessage.success('笔记创建成功')
        }

        // 跳转回笔记列表
        setTimeout(() => {
            goBack()
        }, 1000)
    } catch (error) {
        console.error('保存笔记失败:', error)
        ElMessage.error('保存笔记失败，请稍后重试')
    } finally {
        submitting.value = false
    }
}

// 加载数据
onMounted(async () => {
    await fetchCourses()

    if (isEditing.value) {
        await fetchNoteDetail()
    } else {
        // 如果是新建笔记，获取用户名
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        formData.value.username = studentInfo.username || studentInfo.stu_id
    }
})
</script>

<template>
    <div class="edit-note-page">
        <el-header class="page-header">
            <div class="header-left">
                <el-button icon="ArrowLeft" @click="goBack" text>返回</el-button>
            </div>
            <div class="header-title">
                {{ isEditing ? '编辑笔记' : '新建笔记' }}
            </div>
            <div class="header-right">
                <el-button
                    type="primary"
                    :icon="Check"
                    @click="submitForm"
                    :loading="submitting"
                >
                    保存
                </el-button>
            </div>
        </el-header>

        <el-main>
            <div class="edit-container" v-loading="loading">
                <el-form :model="formData" label-position="top">
                    <el-form-item label="笔记标题">
                        <el-input
                            v-model="formData.note_title"
                            placeholder="请输入笔记标题"
                            maxlength="100"
                            show-word-limit
                        />
                    </el-form-item>

                    <el-form-item label="关联课程">
                        <el-select
                            v-model="formData.course_id"
                            placeholder="选择关联课程（可选）"
                            clearable
                            style="width: 100%"
                        >
                            <el-option
                                v-for="course in courses"
                                :key="course.id"
                                :label="course.name"
                                :value="course.id"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="笔记内容">
                        <el-input
                            v-model="formData.note_content"
                            type="textarea"
                            :rows="12"
                            placeholder="请输入笔记内容..."
                            maxlength="5000"
                            show-word-limit
                        />
                    </el-form-item>
                </el-form>
            </div>
        </el-main>
    </div>
</template>

<style scoped>
.edit-note-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eee;
}

.header-title {
    font-size: 18px;
    font-weight: bold;
}

.edit-container {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
    margin-bottom: 20px;
}
</style>
